/**
 * 
 */
package com.bieber.smartpost.httpcore;

import java.net.HttpCookie;
import java.util.*;

/**
 * @author bieber
 *
 */
public class Header extends HashMap<String,String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5243834092301615429L;

	private Set<HttpCookie> cookies;
	
	private static final String ITEM_SPLIT="; ";

    private static final String COOKIE_KEY="Set-Cookie";
	
	public Header(){
		
	}
	
	public Header(Map<String,List<String>> headerFields){
		cookies = new HashSet<HttpCookie>();
		StringBuffer headerItemStr = new StringBuffer();
		for(Map.Entry<String,List<String>> entry:headerFields.entrySet()){
				headerItemStr.setLength(0);//clear cache string
				if( COOKIE_KEY.equalsIgnoreCase(entry.getKey())){
					continue;
				}else{
					List<String> headerItems =  entry.getValue();
					for(String header:headerItems) {
						headerItemStr.append(header).append(ITEM_SPLIT);
					}
					headerItemStr.setLength(headerItemStr.length()-1);
					put(entry.getKey(),headerItemStr.toString());
				}
		}
	}
	
	public void addCookie(HttpCookie cookie){
		cookies.add(cookie);
	}
	
	public String getHeader(String key){
		return get(key);
	}
	
	public Map<String,String> getHeaders(){
		return this;
	}

	public Set<HttpCookie> getCookies(){
		return Collections.unmodifiableSet(cookies);
	}

	public String toString(){
		StringBuffer sb = new StringBuffer();
		for(Map.Entry<String, String> entry:entrySet()){
			sb.append(entry.getKey()==null?"":entry.getKey()).append(":").append(entry.getValue()).append("\n");
		}
		sb.append(COOKIE_KEY).append(":").append(toCookiesString()).append("\n");
		return sb.toString();
	}

    public String toCookiesString(){
        StringBuffer cookiesStr = new StringBuffer();
        if(cookies!=null){
            for(HttpCookie cookie:cookies){
                cookiesStr.append(cookie.toString()).append(ITEM_SPLIT);
            }
        }
        if(cookiesStr.length()>0){
            cookiesStr.setLength(cookiesStr.length()-ITEM_SPLIT.length());
        }
        return cookiesStr.toString();
    }
 
}
